import json
from flask import Blueprint, jsonify, make_response,request
from flask_cors import cross_origin

from handle.orders import *

orders_bp = Blueprint('orders', __name__)

@orders_bp.route('/', methods=['GET'])
def get_orders():
    request_data={}
    request_data["page"]=int(request.args.get("page"))
    request_data["size"]=int(request.args.get("size"))
    request_data["status"]=request.args.get("status")
    request_data["sku"]=request.args.get("sku")
    request_data['orderid']=request.args.get("orderid")
    data,page_count,totalSize=get_order_list(request_data)
    return json.dumps({"status": 200,"message": "order list","page_count": page_count,"page": request_data["page"],"size": request_data["size"],"totalSize": totalSize,"data": data},sort_keys=False)

@orders_bp.route('/csv', methods=['OPTIONS'])
@cross_origin()
def handle_options_request_3():
    response = jsonify({'message': 'This is the response to OPTIONS request'})
    response.headers.add('Access-Control-Allow-Methods', 'GET, POST')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
    return response

@orders_bp.route('/csv', methods=['POST'])
def get_orders_csv_ps():
    request_data={}
    request_data["page"]=1
    request_data["size"]=9223372036854775807
    request_data["status"]=request.args.get("status")
    request_data["sku"]=request.args.get("sku")
    request_data['orderid']=request.args.get("orderid")
    request_data["IDList"]=request.get_json().get("IDList")
    data,page_count,totalSize=get_order_list(request_data)
    fieldnames = ["OrderID", "Status", "CreatedAt", "UpdatedAt", "SKU", "Amount", "Remarks"]

    # 写入 CSV 文件到内存中
    csv_content = []
    csv_content.append(",".join(fieldnames))  # 写入表头
    for row in data:
        csv_content.append(",".join([str(row[field]) for field in fieldnames]))

    # 将 CSV 数据转换为字符串
    csv_data = "\r\n".join(csv_content).encode("gb18030")  # 使用 GB18030 编码

    # 构建响应
    response = make_response(csv_data)
    response.headers.set("Content-Disposition", "attachment", filename="orders.csv")
    response.headers.set("Content-Type", "text/csv; charset=gb18030")

    # 返回响应
    return response


@orders_bp.route('/csv', methods=['GET'])
def get_orders_csv():
    request_data={}
    request_data["page"]=1
    request_data["size"]=9223372036854775807
    request_data["status"]=request.args.get("status")
    request_data["sku"]=request.args.get("sku")
    request_data['orderid']=request.args.get("orderid")
    data,page_count,totalSize=get_order_list(request_data)
    fieldnames = ["OrderID", "Status", "CreatedAt", "UpdatedAt", "SKU", "Amount", "Remarks"]

    # 写入 CSV 文件到内存中
    csv_content = []
    csv_content.append(",".join(fieldnames))  # 写入表头
    for row in data:
        csv_content.append(",".join([str(row[field]) for field in fieldnames]))

    # 将 CSV 数据转换为字符串
    csv_data = "\r\n".join(csv_content).encode("gb18030")  # 使用 GB18030 编码

    # 构建响应
    response = make_response(csv_data)
    response.headers.set("Content-Disposition", "attachment", filename="orders.csv")
    response.headers.set("Content-Type", "text/csv; charset=gb18030")

    # 返回响应
    return response

@orders_bp.route('/', methods=['OPTIONS'])
@cross_origin()
def handle_options_request():
    response = jsonify({'message': 'This is the response to OPTIONS request'})
    response.headers.add('Access-Control-Allow-Methods', 'GET, POST')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
    return response

@orders_bp.route('/', methods=['POST'])
def create_order():
    request_data=request.get_json()
    data=new_order(request_data)
    return json.dumps({"status": 200,"message": f"create order for SKU: {request_data['SKU']}","data": data},sort_keys=False)



@orders_bp.route('/<order_id>', methods=['GET'])
def get_order(order_id):
    data=get_order_byid(order_id)
    return json.dumps({"status": 200,"message": f"Get order {order_id}","data": data},sort_keys=False)



@orders_bp.route('/<order_id>', methods=['OPTIONS'])
@cross_origin()
def handle_options_request_1():
    response = jsonify({'message': 'This is the response to OPTIONS request'})
    response.headers.add('Access-Control-Allow-Methods', 'GET, POST')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
    return response


@orders_bp.route('/<order_id>', methods=['PUT'])
def update_order(order_id):
    request_data=request.get_json()
    data=update_status_order(order_id,request_data["action"])
    return json.dumps({"status": 200,"message": f"update order: {order_id}","data": data},sort_keys=False)

@orders_bp.route('/<order_id>', methods=['OPTIONS'])
@cross_origin()
def handle_options_request_2():
    response = jsonify({'message': 'This is the response to OPTIONS request'})
    response.headers.add('Access-Control-Allow-Methods', 'GET, POST')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
    return response

@orders_bp.route('/dl', methods=['OPTIONS'])
@cross_origin()
def handle_options_request_5():
    response = jsonify({'message': 'This is the response to OPTIONS request'})
    response.headers.add('Access-Control-Allow-Methods', 'GET, POST')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
    return response

@orders_bp.route('/dl', methods=['DELETE'])
def delete_order_list():
    request_data=request.get_json()
    # IDList=request_data.get("IDList", None)
    if request_data==None:
        return json.dumps({"status": 400,"message": f"Delete order failed"},sort_keys=False)
    else:
        logger.error(request_data)
        for order_id in request_data:
            if del_order(order_id)==False:
                return json.dumps({"status": 400,"message": f"Delete order {order_id} failed"},sort_keys=False)
        return json.dumps({"status": 200,"message": f"Delete order"},sort_keys=False)

@orders_bp.route('/<order_id>', methods=['DELETE'])
def delete_order(order_id):
    if del_order(order_id)==True:
        return json.dumps({"status": 200,"message": f"Delete order {order_id}"},sort_keys=False)
    else:
        return json.dumps({"status": 400,"message": f"Delete order {order_id} failed"},sort_keys=False)
